from datetime import datetime, timedelta
from typing import Annotated, Optional

from fastapi import APIRouter, Depends, BackgroundTasks, Request, Body

from sanren.utils import get_current_active_user, Helper
from application.http import models
from application.http.models import OemModel, CodeModel
from application.http.schemas import ApiSchemas
from application.http import schemas
from application.config import appSettings


router = APIRouter(prefix='/brand/goods', tags=['Brand'])
module_name = '品牌商模块 - 商品'


@router.get('', response_model=schemas.BaseApiListOut)
async def get_goods(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    page_params: schemas.PageParams = Depends(),
    brand_id: Optional[int] = None,
    code: Optional[str] = None,
    keyword: Optional[str] = None,
):
    """
        品牌商 商品列表
    """

    objs = OemModel.Good.with_('brand')

    if brand_id:
        objs = objs.where('brand_id', brand_id)

    if code:
        objs = objs.where('code', code)

    if keyword:
        objs = objs.where(
            lambda query: query.where(
                'brand_id', 'like', f'%{keyword}%'
            ).or_where(
                'good_code', 'like', f'%{keyword}%'
            ).or_where(
                'title', 'like', f'%{keyword}%'
            ).or_where(
                'order_id', 'like', f'%{keyword}%'
            )
        )

    objs = objs.order_by('id', 'desc').paginate(page_params.pageSize, page_params.page)

    return objs.serialize()


@router.post('', response_model=schemas.BaseApiOut)
async def add_good(
    current_user: Annotated[object, Depends(get_current_active_user)],
    background_tasks: BackgroundTasks,
    request: Request,
    post: ApiSchemas.brand.GoodCreate,
):
    """
        添加生码商品
    """

    # 生成商品code
    good_code = ''.join(Helper.random_str(length=10, ctype=2))
    while OemModel.Good.where('good_code', good_code).first():
        good_code = ''.join(Helper.random_str(length=10, ctype=2))

    try:
        obj = OemModel.Good.create(
            good_code=good_code,
            code=post.code.lower(),
            brand_id=post.brand_id,
            title=post.title,
            order_id=post.order_id,
            domain=post.domain,
            desc=post.desc,
            description=post.description,
            user_id=current_user.id,
        )

        print('操作成功:', obj.fresh().id)
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.delete('/delete-batch', response_model=schemas.BaseApiOut)
async def delete_batch_good(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    data: dict = Body(),
):
    """
        批量删除生码商品
    """

    delete_obj = []

    for id in data['ids']:
        # 商品信息
        obj = OemModel.Good.find(id)
        if obj is None:
            return schemas.BaseApiOut(code=1, message='此生码商品不存在')

        # 判断生码单是否使用
        order = CodeModel.Order.where('good_code', obj.good_code).first()
        if order is not None:
            return schemas.BaseApiOut(code=1, message='此商品已经应用在生码单上，不能进行删除操作')

        delete_obj.append(obj)

    try:
        for obj in delete_obj:
            obj.delete()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.get('/{id}', response_model=schemas.BaseApiOut)
async def good_detail(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int | str,
):
    """
        详情 生码商品
    """

    obj = OemModel.Good.find(id)
    if obj is None:
        obj = OemModel.Good.where('good_code', id).first()
        if obj is None:
            return schemas.BaseApiOut(code=1, message='此生码商品不存在')

    return {'data': obj.serialize()}


@router.put('/{id}', response_model=schemas.BaseApiOut)
async def edit_good(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    post: ApiSchemas.brand.GoodCreate,
    id: int,
):
    """
        编辑生码商品
    """

    obj = OemModel.Good.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此生码商品不存在')

    try:
        obj.order_id = post.order_id
        obj.domain = post.domain
        obj.title = post.title
        obj.desc = post.desc
        obj.description = post.description
        obj.save()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}


@router.delete('/{id}', response_model=schemas.BaseApiOut)
async def delete_good(
    current_user: Annotated[object, Depends(get_current_active_user)],
    request: Request,
    id: int,
):
    """
        删除生码商品
    """

    obj = OemModel.Good.find(id)
    if obj is None:
        return schemas.BaseApiOut(code=1, message='此生码商品不存在')

    # 判断生码单是否使用
    order = CodeModel.Order.where('good_code', obj.good_code).first()
    if order is not None:
        return schemas.BaseApiOut(code=1, message='此商品已经应用在生码单上，不能进行删除操作')

    try:
        obj.delete()

        print('操作成功')
    except Exception as e:
        return schemas.BaseApiOut(code=1, message=f'操作失败: {str(e)}')

    return {}
